<template>
  <el-dialog v-model="state.isFalse" title="开锁任务" :before-close="onVisable" :draggable="true" :width="650">
    <el-form ref="formRef" :model="state.form" :rules="state.ruleList" label-width="85px">
      <el-form-item label="任务名称" prop="name">
        <el-input size="large" v-model="state.form.name" placeholder="请输入任务名称" :autosize="{ minRows: 3, maxRows: 5 }" type="textarea"/>
      </el-form-item>
      <el-form-item label="操作人员" prop="userId">
        <el-select v-model="state.form.userId" class="m-2" placeholder="请选择操作人员" size="large" style="width: 100%;" multiple filterable>
          <el-option v-for="item in state.userList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="选择门禁" prop="sensor_id">
        <el-select v-model="state.form.sensor_id" class="m-2" placeholder="请选择操作门禁" size="large" style="width: 100%;">
          <el-option v-for="item in publicStore.list" :key="item.sensor_id" :label="item.name" :value="item.sensor_id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="start_time">
        <el-date-picker
          placeholder="请选择任务开始时间"
          type="datetime"
          v-model="state.form.start_time"
          style="width: 50%;"
          size="large"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          :disabledDate="disabledDateFun"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="end_time" >
        <el-date-picker
          placeholder="请选择任务结束时间"
          type="datetime"
          v-model="state.form.end_time"
          style="width: 50%;"
          size="large"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss"
          :disabledDate="disabledDateFun"
        />
      </el-form-item>
      <el-form-item label="开锁次数" prop="num" >
        <el-radio-group v-model="state.form.num" class="ml-4">
          <el-radio label="1" size="large">一次</el-radio>
          <el-radio label="-1" size="large">多次</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="授权方式" prop="type" >
        <el-radio-group v-model="state.form.type" class="ml-4">
          <el-radio label="0" size="large">密码</el-radio>
          <el-radio label="1" size="large">刷卡</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" class="buttonStyle" @click="onVisable">取 消</el-button>
        <el-button size="large" class="buttonStyle" @click="handleSubmit(formRef)">下一步</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import api from '@/api'
  const { proxy }: any = getCurrentInstance();
  const publicStore = proxy.publicStore();
  const state = reactive({
    ...publicStore.$state,
    ruleList: {
      name: [{ required: true, message: '请输入', trigger: 'blur' }],
      userId: [{ required: true, message: '请选择', trigger:['blur','change']  }],
      sensor_id: [{ required: true, message: '请选择', trigger:['blur','change']  }],
      start_time: [{ required: true, message: '请选择', trigger:['blur','change']  }],
      end_time: [{ required: true, message: '请选择', trigger:['blur','change']  }],
      num: [{ required: true, message: '请选择', trigger:['blur','change'] }],
      type: [{ required: true, message: '请选择', trigger:['blur','change'] }],
    },
    userList: [],
  });
  const emit = defineEmits(['init'])
  let formRef = ref()

  const onVisable = async (val = {}) => {
    state.isFalse = !state.isFalse
    if(!state.isFalse) return
    getUser()
    state.form = Object.assign(({}, val))
  }

  const getUser = async() => {
    let query = {"o": "o_comm_usr",	"i": 0,	"p": [publicStore.distributId]}
    let params = {queryApi: query}
    let res = await publicStore.post(params)
    state.userList = proxy.isNull(res)? '' : res
  }

  const disabledDateFun = (time) => {
    return time.getTime() < Date.now() - 1 * 8.64e7;
  }

  const handleSubmit = (formEl) => {
    formEl.validate(valid => {
      if (valid) {
        let sensor = publicStore.list.find(a=>a.id == state.form.sensor_id)
        let form = Object.assign({}, state.form)
        form.start_time = new Date(form.start_time).getTime() + ''
        form.end_time = new Date(form.end_time).getTime() + ''
        if(form.start_time > form.end_time || form.start_time == form.end_time) return ElNotification({ title: '提示', message: '结束时间必须大于开始时间', type: 'error' })
        form.userName = []
        form.userId.forEach(v => {
          let user = state.userList.find(a=>a.id == v)
          if (user) form.userName.push(user.name)
        })
        form.userName = form.userName.join()
        form.userId = form.userId.join()
        form.sensor_name = sensor.name
        form.stationNum = publicStore.distributId
        form.id = new Date().getTime() + ''
        form.status = '0'
        form.o = 'o_sensor_access'
        form.t = 'add'
        form.a = '添加'
        console.log('form', form)
        api.updateApi([form]).then((res) => {
          if(res.errcode == 0){
            ElNotification({ title: '提示', message: '操作成功', type: 'success' })
            emit('init')
            onVisable()
          }
        }).catch((err) => {
            ElNotification({ title: '提示', message: '操作失败', type: 'error' })
        })
      }
    })
  }

  // 暴露给父组件
  defineExpose({
    onVisable
  })
</script>

<style scoped lang="scss">

</style>
